//
//  ExchangeChatViewController.swift
//  Exchange
//
//  Created by rui on 2018/5/8.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
import ZendeskSDK
enum ExchangeChatFromType {
    case ad
    case order
}

class ExchangeChatViewController: BaseViewController {

    var orderId: Int?
    var adId: Int? 
    
    var adChatId: Int?
    
    var source: ExchangeChatFromType = .ad
    
    private let kTextChatCell = "TextChatTableViewCell"
    private let kTimeChatCell = "TimeChatTableViewCell"
    private let kSystemChatCell = "SystemChatTableViewCell"
    
    var originInputViewY: CGFloat = 0
    
    lazy var viewModel: ChatViewModel = {
        var isOrder = false
        if let orderid = orderId {
            isOrder = true
        }else {
            isOrder = false
        }
        let vm = ChatViewModel(isOrder: isOrder)
        vm.orderId = self.orderId ?? 0
        vm.adId = self.adId ?? 0
        vm.waitOrderId = self.adChatId ?? 0
        vm.reload = {[weak self] in
            self?.reload()
        }
        vm.reloadOrderInfo = {[weak self] in
            self?.reloadOrderInfo()
        }
        return vm
    }()
    
    lazy var orderViewModel: ChatOrderViewModel =  {
        let vm = ChatOrderViewModel()
        vm.controller = self
        vm.response = {[weak self](state,isSuccess,errorMsg)in
            if isSuccess {
                if state == ResponseState.trade_ad_chat_info {
                    self?.reload()
                    self?.initChat()
                }else if state == ResponseState.trade_order_detail {
                    self?.reload()
                    self?.initChat()
                }else if state == ResponseState.trade_evaluate_order {
                    CYMBShow.showMessage(kText("评价成功"))
                    self?.reload()
                }else if state == ResponseState.trade_cancel_order {
                    CYMBShow.showMessage(kText("取消订单成功"))
                    self?.reload()
                }else if state == ResponseState.trade_relese_coin {
                    CYMBShow.showMessage(kText("释放币成功"))
                    self?.reload()
                }else if state == ResponseState.trade_notify_relese_coin {
                    self?.reload()
                }else if state == ResponseState.trade_order_confirmPay {
                    CYMBShow.showMessage(kText("确认付款成功"))
                    self?.reload()
                }
            }else {
                if let msg = errorMsg {
                    CYMBShow.showMessage(msg)
                }else {
                    CYMBShow.showMessage(kText("当前无网络,请检查网络"))
                }
            }
        }
        return vm
    }()

    lazy var chatInput: ChatInputView = {
        let textView = ChatInputView()
        textView.placeholder = kText("输入你想说的…")
        textView.delegate = self
        if isiPhoneX() {
           textView.frame = CGRect(x: 0, y: self.view.height - kChatBarOriginHeight - 34, width: self.view.width, height: kChatBarOriginHeight)
        }else {
            textView.frame = CGRect(x: 0, y: self.view.height - kChatBarOriginHeight, width: self.view.width, height: kChatBarOriginHeight)
        }
        textView.autoresizingMask = [.flexibleWidth,.flexibleTopMargin]
        return textView
    }()

    lazy var tableHeaderView: UIView = {
        if let _  = orderId {
            let header = ExchangeChatHeaderView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 220))
            header.delegate = self
            return header
        }
        let header = ExchangeChatNoOrderHeaderView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 100))
        header.delegate = self
        return header
    }()
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: self.view.bounds, style: .plain)
        table.frame = CGRect(x: 0, y: 0, width: self.view.width, height: self.chatInput.y)
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.delegate = self
        table.dataSource = self
        table.themeBackground = ThemeManager.ThemeColorKeys.margin
        table.tableHeaderView = tableHeaderView
        table.register(TextChatTableViewCell.self, forCellReuseIdentifier: kTextChatCell)
        table.register(TimeChatTableViewCell.self, forCellReuseIdentifier: kTimeChatCell)
        table.register(SystemChatTableViewCell.self, forCellReuseIdentifier: kSystemChatCell)
        table.tableFooterView = UIView()
        table.separatorStyle = .none
        return table
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        initData()
    }

    func initUI() {
        self.automaticallyAdjustsScrollViewInsets = false
        NotificationCenter.default.addObserver(self, selector: #selector(showKeyboard(noti:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(hideKeyboard(noti:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
//        chatInput.frame = CGRect(x: 0, y: <#T##CGFloat#>, width: ksc, height: <#T##CGFloat#>)
        view.addSubview(chatInput)
        view.addSubview(tableView)
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick));
        view.addGestureRecognizer(tap)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: kText("帮助"), style: .plain, target: self, action: #selector(goHelp))
    }
    
    func initData() {
        if let orderId = orderId {
            self.orderViewModel.loadOrderInfo(orderId: orderId)
            self.orderViewModel.updateOrderChatTime(id: orderId)
        }else if let adChatId = adChatId {
            self.orderViewModel.loadAdInfo(adChatId: adChatId)
            self.orderViewModel.updateAdChatTime(id: adChatId)
        }
    }
    
    func initChat() {
        if self.viewModel.isLoadHistoryData {
            return
        }
        let userId = self.orderViewModel.waitDetailModel?.otherUserId ?? 0
        let portrait = self.orderViewModel.waitDetailModel?.portrait ?? self.orderViewModel.orderModel?.portrait ?? ""
        let waitOrderId = self.orderViewModel.waitDetailModel?.waitOrderId ?? 0
        self.viewModel.receiver = userId
        self.viewModel.portrait = portrait
        self.viewModel.waitOrderId = waitOrderId
        self.viewModel.loadHistoryData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.resignResponder()
        if let orderId = orderId {
            self.orderViewModel.updateOrderChatTime(id: orderId)
        }else if let adChatId = adChatId {
            self.orderViewModel.updateAdChatTime(id: adChatId)
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        originInputViewY = chatInput.y
    }
    
    @objc func hideKeyboard(noti: Notification) {
        keyboardChange(hide: true, noti: noti)
    }
    
    @objc func showKeyboard(noti: Notification) {
       keyboardChange(hide: false, noti: noti)
    }
    
    @objc func goHelp() {
        let viewController = ZDKHelpCenterUi.buildHelpCenterOverview()
        let nav = UINavigationController(rootViewController: viewController)
        self.present(nav, animated: true, completion: nil)
        dPrint("goHelp")
    }
    
    func keyboardChange(hide: Bool, noti: Notification) {
        let userInfo = noti.userInfo
        let duration = userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        var safeBottom: CGFloat = 0
        if isiPhoneX() {
            safeBottom = 34
        }
        var inputY = self.view.height - self.chatInput.height - safeBottom
        if hide == false {
            let keyboardF = userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
            let convertFrame = AppWindow.keyboardWindow()!.convert(keyboardF, to: self.view)
            inputY = convertFrame.origin.y - self.chatInput.height
        }
        UIView.animate(withDuration: duration) {
            self.chatInput.y = inputY
            self.tableView.height = inputY
            self.tableView.bottom = self.chatInput.y
        }
        originInputViewY = chatInput.y
    }
    
    @objc func tapClick() {
        self.resignResponder()
    }
    
    ///刷新头部信息
    func reloadHeaderView() {
        if let header = self.tableHeaderView as? ExchangeChatHeaderView {
            header.model = self.orderViewModel.orderModel
        }else if let header = self.tableHeaderView as? ExchangeChatNoOrderHeaderView {
            header.model = self.orderViewModel.waitDetailModel
        }
        self.title = self.orderViewModel.getTitle()
    }
    
    ///刷新
    func reload() {
        self.reloadHeaderView()
        self.tableView.reloadData()
        self.scrollToBottom()
    }
    
    ///重新刷新订单信息
    func reloadOrderInfo() {
        self.orderViewModel.loadOrderInfo(orderId: self.orderId ?? 0)
    }
}

extension ExchangeChatViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = viewModel.dataArray[indexPath.row]
        var cell: BaseChatTableViewCell?
        if model.modelType == .time {
            cell = tableView.dequeueReusableCell(withIdentifier: kTimeChatCell, for: indexPath) as? TimeChatTableViewCell
        }else if model.modelType == .text {
            cell = tableView.dequeueReusableCell(withIdentifier: kTextChatCell, for: indexPath) as? TextChatTableViewCell
        }else if model.modelType == .system {
             cell = tableView.dequeueReusableCell(withIdentifier: kSystemChatCell, for: indexPath) as? SystemChatTableViewCell
        }
        cell?.model = model
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = viewModel.dataArray[indexPath.row]
        return model.cellHeight
    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.resignResponder()
    }
    
    func scrollToBottom(animated: Bool = true) {
        if viewModel.dataArray.count > 0 {
            tableView.scrollToRow(at: IndexPath(row: viewModel.dataArray.count - 1, section: 0), at: .bottom, animated: animated)
        }
    }
}

extension ExchangeChatViewController: OrderChatCellDelegate {
    
    ///申诉
    func appeal() {
        if self.orderViewModel.orderModel?.isAppeal == 1 {
            CYMBShow.showMessage(kText("订单已在申诉中"))
            return
        }
        if let id = self.orderId {
            let controller = AppealViewController()
            controller.viewModel?.tradeId = id
            self.navigationController?.pushViewController(controller, animated: true)
        }else {
            CYMBShow.showMessage(kText("订单不存在"))
        }
    }
    
    ///跳转到我的钱包
    func gotoWallet() {
        let vc = AssetViewController()
        vc.selectIndex = 0
        self.navigationController?.pushViewController(vc, animated: true)
//        return
//        self.navigationController?.popToRootViewController(animated: false)
//        if let tab = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController {
//            tab.selectedIndex = 4
//            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
//                if let nav = tab.viewControllers?.last as? NavigationController {
//                    let vc = AssetViewController()
//                    nav.rui_viewControllers.last?.navigationController?.pushViewController(vc, animated: true)
//                }
//            }
//        }
    }
    
    func releseCoin() {
        ///先判断买家是否标记付款
        if let status =  self.orderViewModel.orderModel?.payStatus, status > 0 {
            GooglePassWordManager.creatGoolPassWord(dataSource: self, style: googleStyle.googlePassWordStyle)
        }else {
            CYMBShow.showMessage("请等待买家确认付款后，再释放货币")
        }
        
    }
    
    func  cancel() {
//        let pop = BuyOrSellCancelPopView.loadFromNib() as! BuyOrSellCancelPopView
//        pop.sure = {
//            self.orderViewModel.cancelOrder(orderId: self.orderId ?? 0)
//        }
//        pop.show()
    }
    
    func OrderChatLeftClick(status: ChatButtonStatus) {
        self.view.endEditing(true)
        if status == .appeal {
            appeal()
        }else if status == .cancel {
            self.cancel()
        }
    }
    
    func OrderChatRightClick(status: ChatButtonStatus) {
        self.view.endEditing(true)
        if status == .appeal {
            appeal()
        }else if status == .canceled {
            
        }else if status == .cancel {
            self.cancel()
        }else if status == .evaluate {
            let pop = BuyOrSellEvaluatePopView.loadFromNib() as! BuyOrSellEvaluatePopView
            pop.sure = {
                let index = Int8(pop.getSelectIndex())
                self.orderViewModel.evaluateOrder(orderId: self.orderId ?? 0, evaluation: index)
            }
            pop.show()
        }else if status == .markPayed {
            let pop = BuyOrSellPaySurePopView.loadFromNib() as! BuyOrSellPaySurePopView
            pop.sure = {
              self.orderViewModel.confirmPay(orderId: self.orderId ?? 0)
            }
            pop.show()
        }else if status == .notifyReleseCoin {
            self.orderViewModel.notifyReleseCoin(orderId: self.orderId ?? 0)
        }else if status == .releseCoin {
            self.releseCoin()
        }else if status == .wallet {
            self.gotoWallet()
        }
    }
    
    func OrderChatSureClick(isEdit: Bool) {
        if isEdit {
            let vc = AdvertViewController()
            let waitModel = self.orderViewModel.waitDetailModel
            vc.viewModel?.isBuyBool = waitModel?.type == 0 ? true : false
            vc.viewModel?.inforId = waitModel?.id
            vc.viewModel?.isChange = true
            self.navigationController?.pushViewController(vc, animated: true)
        } else {
            if self.source == .ad {
                self.navigationController?.popViewController(animated: true)
            }else {
                if let id = self.orderViewModel.waitDetailModel?.id {
                    let vc = BuyOrSellDetailViewController()
                    vc.adId = id
                    self.navigationController?.customReplaceTopPushViewController(vc, animated: true)
                }else {
                    CYMBShow.showMessage(kText("广告不存在"))
                }
            }
        }
    }
    
    
    func OrderChatArrowClick(btn: UIButton) {
        guard let haderView = tableHeaderView as? ExchangeChatHeaderView else { return }
//        haderView.isUnfold = !haderView.isUnfold
        haderView.height = btn.bottom + 36
        self.tableView.tableHeaderView = haderView
        self.tableView.reloadData()
    }   
}

extension ExchangeChatViewController: ChatInputViewDelegate {
    
    func chatInputViewDidBeginEditing(inputView: ChatInputView){
        self.scrollToBottom()
    }
    
    func chatInputViewUpdateHeight(inputView: ChatInputView, height: CGFloat) {
        let offsetY = height - kChatBarOriginHeight
        chatInput.height = height
        chatInput.y = originInputViewY - offsetY
        self.tableView.height = originInputViewY - offsetY
        self.tableView.bottom = originInputViewY - offsetY
        scrollToBottom()
    }
    

    func chatInputViewSend(inputView: ChatInputView) {

        if let text = inputView.textView.text,text.count > 0 {
            viewModel.sendMsg(msg: text)
            inputView.textView.text = ""
        }else {
            CYMBShow.showMessage(kText("聊天内容不能为空"))
        }
    }
    
    func chatReload() {
        self.tableView.reloadData()
        self.scrollToBottom()
    }
    
    func resignResponder() {
        if self.chatInput.textView.isFirstResponder {
            self.chatInput.textView.resignFirstResponder()
        }
    }
}

extension ExchangeChatViewController : GoolPassWordDelegate {
    func googleVerificationt(passWord:String) {
        dPrint(passWord)
        self.orderViewModel.releseCoin(orderId: self.orderId ?? 0, payPassword: passWord)
    }

}
